//
//  FaceAttestationView.m
//  mendianjieke
//
//  Created by 响当当 on 8/7/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "FaceAttestationView.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface FaceAttestationView()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong)UIImageView *successImageView;//
@property (nonatomic, strong)UIButton *imageViewBtn;//添加图片
@property (nonatomic, strong)UIButton *addBtn;//上传
@property (nonatomic, strong)NSString *baseString;//上传
@end

@implementation FaceAttestationView

- (UIButton *)imageViewBtn
{
    if (!_imageViewBtn)
    {
        
        UILabel *titleLabel = [Utilties creatLabelWithFrame:CGRectMake(15*kUIScaleBasePlus,15*kUIScaleBasePlus,SCREEN_WIDTH-30*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                               textAligment:NSTextAlignmentLeft
                                                   textClor:LCHexColor(0x282828)
                                                   textFont:15*kUIScaleBasePlus];
        titleLabel.text = @"请上传您的正面照片";
        [self addSubview:titleLabel];
        
        _imageViewBtn = [Utilties creatButtonWithFrame:CGRectMake(15*kUIScaleBasePlus,CGRectGetMaxY(titleLabel.frame)+20*kUIScaleBasePlus,345*kUIScaleBasePlus,138*kUIScaleBasePlus)
                                          textAligment:UIControlContentHorizontalAlignmentCenter
                                                  text:@""
                                              textClor:LCHexColor(0x000000)
                                             buttonBGC:[UIColor clearColor]
                                              textFont:12
                                                target:self
                                                method:@selector(addImageView:)];
        [_imageViewBtn setImage:[UIImage imageNamed:@"tianjiazhaopian"] forState:UIControlStateNormal];
        
        UILabel *label = [Utilties creatLabelWithFrame:CGRectMake(0,CGRectGetMaxY(self.imageViewBtn.frame)+20*kUIScaleBasePlus,SCREEN_WIDTH,37*kUIScaleBasePlus)
                                          textAligment:NSTextAlignmentCenter
                                              textClor:LCHexColor(0x989898)
                                              textFont:12*kUIScaleBasePlus];
        label.backgroundColor = LCHexColor(0xFFEEE2);
        label.text = @"请上传正对手机，并且光线充足的照片";
        [self addSubview:label];
    }
    return _imageViewBtn;
}

- (UIButton *)addBtn
{
    if (!_addBtn)
    {
        _addBtn = [Utilties creatButtonWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(self.imageViewBtn.frame)+92*kUIScaleBasePlus,315*kUIScaleBasePlus,40*kUIScaleBasePlus)
                                    textAligment:UIControlContentHorizontalAlignmentCenter
                                            text:@"确认上传"
                                        textClor:LCHexColor(0xFFFFFF)
                                       buttonBGC:LCHexColor(0xFF7A17)
                                        textFont:17*kUIScaleBasePlus
                                          target:self
                                          method:@selector(add:)];
        _addBtn.layer.masksToBounds = YES;
        _addBtn.layer.cornerRadius = _addBtn.frame.size.height/2;
    }
    return _addBtn;
}

- (UIImageView *)successImageView
{
    if (!_successImageView)
    {
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,255*kUIScaleBasePlus)];
        footView.backgroundColor = [UIColor whiteColor];
        [self addSubview:footView];
        
        _successImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-25*kUIScaleBasePlus,31*kUIScaleBasePlus,50*kUIScaleBasePlus,50*kUIScaleBasePlus)];
        _successImageView.image = [UIImage imageNamed:@"chenggong"];
        
        UILabel *titleLabel = [Utilties creatLabelWithFrame:CGRectMake(SCREEN_WIDTH/2-60*kUIScaleBasePlus,CGRectGetMaxY(_successImageView.frame)+10*kUIScaleBasePlus,120*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                               textAligment:NSTextAlignmentCenter
                                                   textClor:LCHexColor(0x282828)
                                                   textFont:16*kUIScaleBasePlus];
        titleLabel.text= @"认证成功";
        [self addSubview:titleLabel];
    }
    return _successImageView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self addSubview:self.imageViewBtn];
        [self addSubview:self.addBtn];
    }
    return self;
}

- (void)addImageView:(UIButton *)sender
{
    
    
    WeakSelf(self)
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil
                                                                                 message:nil
                                                                          preferredStyle:UIAlertControllerStyleActionSheet];
                
        /// 取消
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                                       style:UIAlertActionStyleCancel
                                                                     handler:^(UIAlertAction * _Nonnull action) {
                                                                     }];
        /// 相册
        UIAlertAction *photoAlbumAction = [UIAlertAction actionWithTitle:@"相册"
                                                                           style:UIAlertActionStyleDefault
                                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                                             [weakSelf openPhoto];
                                                                         }];
        /// 拍照
        UIAlertAction *takingPicturesAction = [UIAlertAction actionWithTitle:@"拍照"
                                                                               style:UIAlertActionStyleDefault
                                                                             handler:^(UIAlertAction * _Nonnull action) {
                                                                                 [weakSelf openCamera];
                                                                             }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:takingPicturesAction];
        [alertVC addAction:photoAlbumAction];
                /// 展示

        [[Utilties getCurrentVC] presentViewController:alertVC animated:YES completion:nil];
}

//打开相册
- (void)openPhoto
{
    // 用户开放相机权限后 判断相机是否可用
         BOOL useable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
         
         if (useable)
         {
             [self openSuccWithPhoto];
         }
         else
         {
             [self guideUserOpenAuth];
         }
}

- (void)openCamera
{
        AVAuthorizationStatus avStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (avStatus == kCLAuthorizationStatusRestricted || avStatus == kCLAuthorizationStatusDenied)
    {
        //无权限
        return;
    }
      
      // 用户开放相机权限后 判断相机是否可用
      BOOL useable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
      
      if (useable)
      {
          [self openSuccWithCamera];
      }
      else
      {
          [self guideUserOpenAuth];
      }
}

// 打开相机
- (void)openSuccWithPhoto
{
    
    UIImagePickerController *photoPicker = [UIImagePickerController new];
    photoPicker.delegate = self;
    photoPicker.allowsEditing = NO;
    
    photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [[Utilties getCurrentVC] presentViewController:photoPicker animated:YES completion:^{
        
    }];
}

// 打开相机
- (void)openSuccWithCamera
{
    
    UIImagePickerController *photoPicker = [UIImagePickerController new];
    photoPicker.delegate = self;
    photoPicker.allowsEditing = NO;
    
    photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    photoPicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    
    [[Utilties getCurrentVC] presentViewController:photoPicker animated:YES completion:^{
        
    }];
}

- (void)guideUserOpenAuth
{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请打开访问权限" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *act = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 引导用户设置
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        }
    }];
    [alertC addAction:alertA];
    [alertC addAction:act];
    [[Utilties getCurrentVC] presentViewController:alertC animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage * image;
        // 判断，图片是否允许修改
        if ([picker allowsEditing]){
            //获取用户编辑之后的图像
            image = [info objectForKey:UIImagePickerControllerEditedImage];
        } else {
            // 照片的元数据参数
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        // 压缩图片
        UIImage *compressImg = [self compressPictureWith:image];
        [self.imageViewBtn setImage:image forState:UIControlStateNormal];
        //        NSLog(@"%@",NSStringFromCGSize(compressImg.size));
        // 用于上传
        NSData *tmpData = UIImageJPEGRepresentation(compressImg, 0.5);
        NSString *base64String = [tmpData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        self.baseString = base64String;
        
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    
}

// 压缩图片
- (UIImage *)compressPictureWith:(UIImage *)originnalImage
{
    CGFloat ruleWidth = 300;
    if (originnalImage.size.width < ruleWidth)
    {
        return originnalImage;
    }
    
    CGFloat hight = ruleWidth/originnalImage.size.width * originnalImage.size.height;
    CGRect rect = CGRectMake(0, 0, ruleWidth, hight);
    // 开启图片上下文
    UIGraphicsBeginImageContext(rect.size);
    // 将图片渲染到图片上下文
    [originnalImage drawInRect:rect];
    // 获取图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图片上下文
    UIGraphicsEndImageContext();
    return img;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [[Utilties getCurrentVC] dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)result:(NSString *)num
{
    if (num.integerValue == 1)
    {
        self.imageViewBtn.hidden = YES;
        self.addBtn.hidden = YES;
        [self addSubview:self.successImageView];
    }
    else
    {
        self.imageViewBtn.hidden = NO;
        self.addBtn.hidden = NO;
        [SVProgressHUD showErrorWithStatus:@"上传失败，请重新上传"];
    }
}

- (void)add:(UIButton *)sender
{
    
    if (!self.baseString)
    {
        DISMISS_SVP(1.0)
        [SVProgressHUD showErrorWithStatus:@"请先上传您的照片"];
        return ;
    }
    
    NSDictionary *pramaters = @{
                                @"img" : self.baseString
                                };
    
    WeakSelf(self)
    [infoManager postFaceInfo:pramaters
                       sucess:^(id  _Nonnull acceptData) {
                           
                           //                                  NSNumber *num = acceptData[@"data"];
                           [weakSelf result:@"1"];
                           
                       }
                         fail:^(NSError * _Nullable error) {
                             
                         }];
}


@end
